<template>
  <div>
    <!-- 索赔结算发票提报查询-详情页面 -->
    <BreakSpace label="结算单信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="formPanel"
      :list="formList"
      :cols="3"
      :formType="'add'"
      labelWidth="110"
      :isSubmitBtn="false"
      @formChange="formChangeHandle"
    />
    <div style="padding-top: 3rem"></div>
    <BreakSpace label="索赔信息" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :columns="columns"
      :dataSource="dataList"
      :params="fetchParams"
      :datakey="'data'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :isPagination="false"
      :isSelectColumn="false"
      height="auto"
      :is-select-column="false"
    ></FilterTable>
    <FilterTable
      ref="table2"
      :isColumnFilter="false"
      selectionType="single"
      :dataSource="reportInfo"
      :datakey="'items'"
      :isSelectColumn="false"
      :isToperInfo="false"
      :isPagination="false"
      :columns="columnsReport"
      :onColumnsChange="columns => (this.columnsReport = columnsReport)"
      :onRowSelectChange="selectChange"
      height="auto"
    ></FilterTable>

    <BreakSpace label="发票信息" :containerStyle="{ marginBottom: '10px' }" />

    <FilterTable
      ref="invoiceInfo"
      :dataSource="invoiceInfo"
      :columns="columnsInvoice"
      :onColumnsChange="(columns) => (this.columnsInvoice = columnsInvoice)"
      :onRowSelectChange="selectChange"
      :isSelectColumn="false"
      height="auto"
    ></FilterTable>

    <!-- 附件信息 -->
    <BreakSpace label="附件信息" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
          ref="fileTable"
          :columns="columnsFile"
          columnsRef="whbydUploadFile"
          :isSelectColumn="false"
          :onColumnsChange="columnsFile => (this.columnsFile = columnsFile)"
          height="auto"
        />
    <div style="padding-top: 3rem"></div>

    <!-- 审核信息 -->
    <BreakSpace label="审核信息" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
          ref="auditHistoryTable"
          :columns="columnsAuditHistory"
          columnsRef="auditHistory"
          :isSelectColumn="false"
          :onColumnsChange="columnsAuditHistory => (this.columnsAuditHistory = columnsAuditHistory)"
          height="auto"
        />
    <div style="padding-top: 3rem"></div>

    <!-- 物流信息 -->
    <BreakSpace label="物流信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="logisticsPanel"
      :list="logisticsList"
      :cols="4"
      :formType="'add'"
      labelWidth="110"
      :isSubmitBtn="false"
      @formChange="formChangeHandle"
    />
    <div style="padding-top: 3rem"></div>
    <el-button type="primary" @click="closeDialog">关 闭</el-button>
    
  </div>
</template>
<script>
import { isFormEmpty } from '@/utils/index';
import { getCloseAccountCount, getPartType, getClaimInfoByNo, getCostCountByNo, editSave, quyrpBatch, updateBusinessMoney, getCbClaim } from '@/api/claim/factory/ClaimStatementQueryFactory';
// import { getCloseAccountCount, getPartType, getClaimInfoByNo, getCostCountByNo } from '@/api/coordinate/claimSettleClose';
// import { approve,quyrpBatch} from '@/api/claim/factory/ClaimInvoiceCheck';
import { dictionary } from '@/utils/dictMixin';
import { getCodeType, queryClaimPageInfoBySettleNo, queryClaimInvoiceInfoBySettleNo,queryLogisticsInfoBySettleNo,queryInvoiceType,queryFileInfoBySettleNo,getAuditHistory} from '@/api/claim/factory/claimStatamentInvoiceAudit';
import { findFileByUrl } from '@/api/partsmanage/financialManagement/capitalAccount/index'
export default {
  mixins: [dictionary],
  props: ['rowData'],
  components: {
    //uploadFile
  },
  data() {
    return {
      dataList: [],
      reportInfo: [],
      invoiceInfo: [],
      dataList1: [],
      kaohesum: 0,
      suopeisum: 0,
      huanxiajiandataList: [],
      fujiaxiangmudataList: [],
      openPartSettleSubmitPage: false,
      //索赔单列表开关
      suopeidanFlag: false,
      kaohedanFlag: false,
      visibleDrawer: false,
      collapse: false,
      infoId: null,
      printList: {
        rows: [{}]
      },
      flterValue: {}, //参数
      columns: this.creatHeader(),
      columnsReport: this.creatHeaderReport(),
      columnsInvoice: this.creatInvoiceTable(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      selectedFaPiaoRow: [], //发票选中
      formList: this.createFormList(),
      logisticsList: this.createLogisticsList(),
      columnsFile: this.createdFileTable(),
      columnsAuditHistory: this.createdAuditHistoryTable(),
      editRow: {},
      saveData: null,
      upVisible: false,
      assessId: null
    };
  },
  async created() {
    await this.findBuyItems();
    this.tableInfo();
    this.claimTableInfo();
    this.queryLogisticsInfo();
    this.queryInvoiceTypeInfo();
    this.queryFileInfo();
    this.queryAuditHistoryInfo();
  },
  methods: {
    formChangeHandle(val) {
      this.saveData = val;
    },

    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
    },
    //发票表格
    selectChangeFaPiao(rows) {
      this.selectedFaPiaoRow = rows;
    },
    async claimTableInfo() {
      let data = {};
      let res = await queryClaimPageInfoBySettleNo(this.rowData.settleNo);
      console.log('===================' + JSON.stringify(res) + 'res++++++++++++++++');
      //为table赋值(索赔单)
      if (200 == res.resultCode) {
        data = res.data;
        if (isFormEmpty(data)) {
          data = {};
        }
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(data);
      }
    },
    async tableInfo() {
      const res = await getCodeType({ type: 5010 });
      if (res.resultCode == 200) {
        this.columnsReport.find(x => x.dataIndex == 'invoiceType').initialValue = '';
        this.columnsReport.find(x => x.dataIndex == 'invoiceType').editItems = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },

    //打印材料费结算单
    async pratDocuments() {
      //let res = await getClaimInfoByNo(this.rowData.settleNo);
      let arr = [];
      arr.push(this.printList.rows);
      this.printList.rows = arr;
      this.$nextTick(() => {
        this.$refs.templatePartBils.EXCUTE_PRINT();
      });
      console.log("模板数据输出+++++++"+JSON.stringify(this.printList.rows))
    },

    async queryFileInfo(){
        //查询附件信息
        let resData = await queryFileInfoBySettleNo(this.rowData.settleNo);
        if(resData.resultCode == 200){
          this.$refs.fileTable.$refs.pageTable.EXECUTE_INSERT(resData.data);
        }
    },

    async queryAuditHistoryInfo(){
        //查询审核信息
        let resData = await getAuditHistory(this.rowData.settleNo);
        if(resData.resultCode == 200){
          this.$refs.auditHistoryTable.$refs.pageTable.EXECUTE_INSERT(resData.data);
        }
    },

     // 获取服务端文件 to blob
    async downLoadByUrl(url, params = {}) {
      let res = await findFileByUrl(url);
      console.log(res.data)
      return res.data;
    },
    // 执行下载动作
    async downloadFile(url) {
      console.log(url)
      const data = await this.downLoadByUrl(url);
      console.log('downloadUrl=====', data)
      let a = document.createElement('a');
      a.href = data;
      a.target = '_blank';
      a.click();
      a = null;
    },

    async queryInvoiceTypeInfo(){
        //开票信息
        let invoiceData = null;
        let resData = await queryInvoiceType(this.rowData.settleNo);
        if (200 == resData.resultCode) {
          invoiceData = resData.data;
          this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(invoiceData);
        }
    },
    async queryLogisticsInfo(){
        //查询物流信息
        let logisticsData = null;
        let resData = await queryLogisticsInfoBySettleNo(this.rowData.settleNo);
        if (200 == resData.resultCode) {
          logisticsData = resData.data;
          this.logisticsList.map(a =>{
              a.initialValue = logisticsData[a.fieldName];
          })
        }
    },
    //给input框赋值
    async findBuyItems() {
      this.formList.map(x => {
        if (x.fieldName == 'finalStatementType') {
          x.initialValue = this.createDictText(this.rowData[x.fieldName], '5002');
        } else {
          x.initialValue = this.rowData[x.fieldName];
        }
      });

      let data = {};
      let res = await queryClaimInvoiceInfoBySettleNo(this.rowData.settleNo);
      //为table赋值(索赔单)
      if (200 == res.resultCode) {
        data = res.data;
        if (isFormEmpty(data)) {
          data = {};
          this.invoiceTableInfo = [
            {
              batteryMaintenanceId: 0,
              invoiceBatchNumber: '',
              invoiceNumber: '',
              money: '',
              taxes: '',
              amount: '',
              invoiceDate: ''
            }
          ];
        }
        this.$refs.invoiceInfo.$refs.pageTable.EXECUTE_INSERT(data);
      }
      let list = this.$refs.table.$refs.pageTable.list;

      let params = {
        invoiceList : data,
        claimList :list,
        dealerCode:this.rowData.dealerCode,  //服务中心代码
        dealerName:this.rowData.dealerName,  //服务中心名称
      };
    this.printList.rows = Object.assign(params,this.printList.rows);
    },

    //取消操作
    closeDialog() {
      this.$emit('close', { openPartSettleSubmitPage: false, data: this.selectedRows, type: 'close' });
    },
    editFile(row) {
      this.upVisible = true;
      this.assessId = row.assessId;
    },
    chooseOrderNo() {
      this.openPartSettleSubmitPage = true;
    },

    createLogisticsList() {
      return [
        {
          type: 'INPUT',
          label: '物流/快递公司',
          fieldName: 'logisticsName',
          selfCols:2,
          disabled: true // 只读
        },
        {
          type: 'INPUT',
          label: '物流/快递单号',
          fieldName: 'logisticsNo',
          selfCols:2,
          disabled: true // 只读
        }
      ];
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'settleNo',
          disabled: true // 只读
        },
        {
          type: 'INPUT',
          label: '服务站代码',
          fieldName: 'dealerCode',
          disabled: true // 只读
        },
        {
          type: 'INPUT',
          label: '服务站名称',
          fieldName: 'dealerName',
          disabled: true // 只读
        },
        {
          type: 'INPUT',
          label: '结算单类型',
          fieldName: 'finalStatementType',
          disabled: true, // 只读
          itemList: this.createDictList('5002')
        },
        {
          type: 'INPUT',
          label: '结算月份',
          fieldName: 'settleDate',
          disabled: true // 只读
        },
        {
          type: 'INPUT_NUMBER',
          label: '结算金额',
          fieldName: 'settleAmount',
          precision: 2, 
          disabled: true // 只读
        }
      ];
    },
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '车型', dataIndex: 'modelName' },
        // { title: '项目', dataIndex: 'projectName' },
        { title: '索赔单数', dataIndex: 'claimCount',  summation: true },
        { title: '保修材料费(元)', dataIndex: 'warrantyAmount', precision: 2, summation: true },
        { title: '保养材料费(元)', dataIndex: 'firstMaintenanceCount', precision: 2, summation: true },
        { title: '合计', dataIndex: 'partAmountSum',  precision: 2, summation: true }
        //{ title: '合计', dataIndex: '合计' },
      ];
    },

    creatHeaderReport() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '发票类别',
          dataIndex: 'orderType',
          minWidth: 120,
          // editable: true,
          // defaultEditable: true,
          showOverflowTooltip: true,
          dictItems: this.createDictList('5010'),
          render: props => {
            return <span>{this.createDictText(props.row.orderType, '5010')}</span>;
          }
        //   editRequired: true,
        //   editType: 'select',
        //   editItems: []
        },
        {
          title: '结算比例',
          dataIndex: 'settleRate',
          initialValue: '0',
          
        //   render: props => {
        //     return this.claimRatio(props);
        //   }
        },
       { title: '误判金额(元)', dataIndex: 'cbPartAmount',  precision: 2, summtion: true },
       {
          title: '开票金额(元)',
          dataIndex: 'invoiceAmount',
          initialValue: '0',
          
          precision: 2,
          //summtion: true
          // render: (props) => {
          //     return this.invoiceMoney(props);
          //   },
        }
        //{ title: '合计', dataIndex: '合计' },
      ];
    },

    creatInvoiceTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 50,
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '发票批号',
          dataIndex: 'invoiceBatchNumber',
        },
        {
          title: '发票号码',
          dataIndex: 'invoiceNumber',
        },
        {
          title: '金额(元)',
          dataIndex: 'money',
          precision: 2
        },
        { title: '税率(%)', dataIndex: 'rate',precision: 2},
        { title: '税额(元)', dataIndex: 'taxes',precision: 2},
        {
          title: '合计(元)',
          dataIndex: 'orderAmountSum',
          precision: 2
        //   render: props => {
        //     return this.summation(props);
        //   }
        },
        { title: '开票日期', dataIndex: 'invoiceDate', filterType: 'date-range',  editType: 'date-picker', dateFormat: 'yyyy-MM-dd' }
        //{ title: '合计', dataIndex: '合计' },
      ];
    },
    createdFileTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '附件标题',
          dataIndex: 'title',
          showOverflowTooltip: true,
          render: p => {
            return (
              // <a style="color:#bb0a30" href={p.row.fileUrl} target="_blank" download={p.row.title}>
              //   {p.row.title}
              // </a>
              <div>
                <el-button style="color:#bb0a30" size="mini" type="text" onClick={() => this.downloadFile(p.row.fileUrl)}>
                  {p.row.title}
                </el-button>
              </div>
            );
          }
        },
        {
          title: '上传日期',
          dataIndex: 'createdAt'
        }
      ];
    },

    createdAuditHistoryTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '签收结果',
          dataIndex: 'checkStatus',
          showOverflowTooltip: true,
          dictItems: this.createDictList('5005')
        },
        {
          title: '签收意见',
          dataIndex: 'checkRemarks',
        },
        {
          title: '签收人',
          dataIndex: 'checkBy',
        },
        { title: '签收时间', dataIndex: 'checkAt'},
      ];
    },
  }
};
</script>
<style lang="less" scoped></style>
